from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .models import Pet, PetType, AdoptionApplication
from .forms import AdoptionApplicationForm
from django.contrib.auth.forms import UserCreationForm
# 宠物列表页
def pet_list(request):
    pets = Pet.objects.all()
    pet_types = PetType.objects.all()

    # 筛选逻辑
    type_id = request.GET.get('type')
    status = request.GET.get('status', 'available')
    if type_id:
        pets = pets.filter(type_id=type_id)
    if status:
        pets = pets.filter(status=status)

    return render(request, 'pets/list.html', {
        'pets': pets,
        'pet_types': pet_types
    })


# 宠物详情页
def pet_detail(request, pk):
    pet = get_object_or_404(Pet, pk=pk)
    return render(request, 'pets/detail.html', {'pet': pet})


# 提交领养申请
@login_required
def apply_adoption(request, pet_id):
    pet = get_object_or_404(Pet, id=pet_id)
    if pet.status != 'available':
        return redirect('pet_detail', pk=pet_id)  # 非可领养状态不允许申请

    if request.method == 'POST':
        form = AdoptionApplicationForm(request.POST)
        if form.is_valid():
            application = form.save(commit=False)
            application.pet = pet
            application.applicant = request.user
            application.save()
            pet.status = 'pending'  # 改为审核中
            pet.save()
            return redirect('application_list')
    else:
        form = AdoptionApplicationForm()

    return render(request, 'pets/apply.html', {
        'form': form,
        'pet': pet
    })


# 我的领养申请
@login_required
def application_list(request):
    applications = AdoptionApplication.objects.filter(applicant=request.user).order_by('-created_time')
    return render(request, 'pets/application_list.html', {'applications': applications})



def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
    else:
        form = UserCreationForm()
    return render(request, 'users/register.html', {'form': form})


# Create your views here.

# 首页视图
def home(request):
    # 获取最新的6个宠物（包括所有状态）
    latest_pets = Pet.objects.order_by('-created_time')[:6]
    # 获取宠物类型数量统计
    pet_types_count = PetType.objects.count()
    # 获取可领养宠物总数
    available_pets_count = Pet.objects.filter(status='available').count()
    # 获取已成功领养的宠物数量
    adopted_pets_count = Pet.objects.filter(status='adopted').count()
    
    return render(request, 'home.html', {
        'latest_pets': latest_pets,
        'pet_types_count': pet_types_count,
        'available_pets_count': available_pets_count,
        'adopted_pets_count': adopted_pets_count
    })